<template>
  <el-dialog
    :title="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'"
    :close-on-click-modal="false"
    append-to-body
    :visible.sync="visible"
    class="jsbos-dialog jsbos-dialog_center"
    lock-scroll
    width="800px"
  >
    <el-row :gutter="15" class="">
      <el-form
        ref="elForm"
        :model="dataForm"
        :rules="rules"
        size="small"
        label-width="100px"
        label-position="right"
      >
        <template v-if="!loading">
          <el-col :span="24">
            <el-form-item label="调查模板" prop="questionnaireName">
              <el-select
                v-model="dataForm.questionnaireName"
                placeholder="请选择"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in questionnaireIds"
                  :key="index"
                  :label="item.questName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="调查编码" prop="orderCode">
              <el-input
                v-model="dataForm.orderCode"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
                maxlength="25"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="调查标题" prop="orderName">
              <el-input
                v-model="dataForm.orderName"
                placeholder="请输入"
                clearable
                :style="{ width: '100%' }"
                maxlength="25"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开放类型 " prop="orderType">
              <el-radio-group v-model="dataForm.orderType" size="small">
                <el-radio
                  v-for="(item, index) in orderTypeOptions"
                  :key="index"
                  :label="item.enCode"
                  :disabled="item.disabled"
                >
                  {{ item.fullName }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dataForm.orderType == 'internal'">
            <el-form-item label="内部包含范围" prop="orderRange">
              <!-- <dep-select v-model="dataForm.orderRange" placeholder="请选择" clearable filterable :multiple="true">
              </dep-select> -->
              <filterSelect
                width="500px"
                v-model="dataForm.orderRange"
              ></filterSelect>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="时间范围" prop="orderStartAndEndDate">
              <el-date-picker
                v-model="dataForm.orderStartAndEndDate"
                placeholder="请选择"
                clearable
                :style="{ width: '100%' }"
                type="datetimerange"
                :picker-options="pickerOption"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="timestamp"
                :editable="false"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调查描述" prop="description">
              <el-input
                v-model="dataForm.description"
                placeholder="请输入"
                :style="{ width: '100%' }"
                true
                type="textarea"
                :autosize="{ minRows: 3, maxRows: 4 }"
                maxlength="225"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="有效状态" prop="enabledMark">
              <el-radio-group v-model="dataForm.enabledMark" size="small">
                <el-radio
                  v-for="(item, index) in enabledMarkOptions"
                  :key="index"
                  :label="item.enCode"
                  :disabled="item.disabled"
                >
                  {{ item.fullName }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取 消</el-button>
      <el-button
        type="primary"
        @click="dataFormSubmit()"
        v-if="!isDetail"
        :loading="btnLoading"
      >
        确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import request from "@/utils/request";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import { isEmpty } from "@/utils/isEmpty";
import { getOrderTypeList } from "../api";
import formValidate from "@/utils/formValidate";
export default {
  components: {},
  props: [],
  data() {
    // 查询编码重复
    // const validateCode = (rule, value, callback) => {
    //   var form = {
    //     code: value,
    //     name: "",
    //   };
    //   getOrderTypeList(form).then((response) => {
    //     var flag = response.data;
    //     if (!isEmpty(this.dataForm.id)) {
    //       if (
    //         isEmpty(flag) ||
    //         (flag.length == 1 && flag[0].id == this.dataForm.id)
    //       ) {
    //         callback();
    //       } else {
    //         callback(new Error("编码重复"));
    //       }
    //     } else {
    //       if (isEmpty(flag)) {
    //         callback();
    //       } else {
    //         callback(new Error("编码重复"));
    //       }
    //     }
    //   });
    // };
    // 查询分类名称重复
    const validateName = (rule, value, callback) => {
      var form = {
        code: "",
        name: value,
      };
      getOrderTypeList(form).then((response) => {
        var flag = response.data;
        if (!isEmpty(this.dataForm.id)) {
          if (
            isEmpty(flag) ||
            (flag.length == 1 && flag[0].id == this.dataForm.id)
          ) {
            callback();
          } else {
            callback(new Error("名称重复"));
          }
        } else {
          if (isEmpty(flag)) {
            callback();
          } else {
            callback(new Error("名称重复"));
          }
        }
      });
    };
    return {
      pickerOption: {
        disabledDate: (time) => {
          return Date.now() - 3600 * 1000 * 24 > time.getTime();
        },
      },
      list: [
        { type: "company", selectArr: [] },
        {
          type: "department",
          selectArr: [],
        },
        {
          type: "Role",
          selectArr: [],
        },
        {
          type: "Position",
          selectArr: [],
        },
        {
          type: "Group",
          selectArr: [],
        },
        {
          type: "user",
          selectArr: [],
        },
        {
          type: "exclude",
          selectArr: [],
        },
      ],
      btnLoading: false,
      visible: false,
      loading: false,
      isDetail: false,
      questionnaireIds: [],
      dataForm: {
        orderType: "",
        questionnaireName: "",
        questionnaireId: "",
        orderName: "",
        orderCode: "",
        orderRange: [],
        orderStartDate: undefined,
        orderEndDate: undefined,
        orderStartAndEndDate: [],
        enabledMark: "10",
        description: "",
        creatorUserId: "",
        creatorTime: "",
      },
      orderTypeOptions: [],
      rules: {
        questionnaireName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        orderStartAndEndDate: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        enabledMark: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
        // orderCode: [
        //   {
        //     required: true,
        //     message: "请输入",
        //     trigger: "blur",
        //   },
        //   { validator: validateCode, trigger: "blur" },
        //   { validator: formValidate("enCode"), trigger: "blur" },
        // ],
        orderName: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
          { validator: validateName, trigger: "blur" },
        ],
        orderType: [
          {
            required: true,
            message: "请输入",
            trigger: "blur",
          },
        ],
      },
      enabledMarkOptions: [{ fullName: "生效中", enCode: "10" }],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getorderTypeOptions();
    this.getenabledMarkOptions();
    this.getQuestionnaireTemplateList();
  },
  mounted() {},
  methods: {
    //获取问卷模板list
    getQuestionnaireTemplateList() {
      let _query = {
        currentPage: 1,
        pageSize: 200,
        sort: "desc",
        sidx: "creatorTime",
      };
      request({
        url: `/api/questionnaire/OqQuestionnaire/getList`,
        method: "post",
        data: _query,
      }).then((res) => {
        this.questionnaireIds = res.data.list;
      });
    },
    getenabledMarkOptions() {
      getDictionaryDataSelector("471639537894912325").then((res) => {
        this.enabledMarkOptions = res.data.list;
      });
    },
    getorderTypeOptions() {
      getDictionaryDataSelector("436127844121187333").then((res) => {
        this.orderTypeOptions = res.data.list;
      });
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
      this.dataForm.enabledMark = "1";
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          request({
            url: "/api/questionnaire/OqQuestionnaireOrder/" + this.dataForm.id,
            method: "get",
          }).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.enabledMark = "10";
          this.dataForm.orderRange = this.list;
        }
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          this.request();
        }
      });
    },
    request() {
      var _data = this.dataList();
      if (!this.dataForm.id) {
        _data.questionnaireId = _data.questionnaireName;
        if (!isEmpty(this.dataForm.orderStartAndEndDate)) {
          _data.orderStartDate = this.dataForm.orderStartAndEndDate[0];
          _data.orderEndDate = this.dataForm.orderStartAndEndDate[1];
        }
        request({
          url: "/api/questionnaire/OqQuestionnaireOrder",
          method: "post",
          data: _data,
        }).then((res) => {
          this.btnLoading = false;
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      } else {
        request({
          url: "/api/questionnaire/OqQuestionnaireOrder/" + this.dataForm.id,
          method: "PUT",
          data: _data,
        }).then((res) => {
          this.btnLoading = false;
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      }
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      if (_data.orderType == "public") {
        _data.orderRange = [];
      }
      _data.orderRange = JSON.stringify(_data.orderRange);

      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      console.log("---", _dataAll.orderRange);
      _dataAll.orderRange = JSON.parse(_dataAll.orderRange);
      if (_dataAll.orderRange.length === 0) {
        _dataAll.orderRange = this.list;
      }
      console.log("---", _dataAll.orderRange);
      this.dataForm = _dataAll;
    },
  },
};
</script>
